<?php

namespace app\model\user;

use app\base\BaseModel;
use app\factory\wxPay\CompanyPay;
use app\factory\wxPay\WxV3Pay;
use app\model\order\PayLogModel;
use think\model\concern\SoftDelete;

/**
 * 模型-UserEarningsModel
 * Class UserEarningsModel
 * @package app\model
 */
class UserEarningsModel extends BaseModel
{
    use SoftDelete;

    protected $name = 'user_earnings';

    /**
     * 范围查询-status
     * @param $query
     * @param $user_id
     */
    public function scopeUserId($query, $user_id)
    {
        if (!empty($keyword)) {
            $query->where(['user_id' => $user_id]);
        }
    }

    /**
     * 范围查询-status
     * @param $query
     * @param $user_id
     */
    public function scopeKeyword($query, $keyword)
    {
        if (!empty($keyword)) {
            $query->whereLike('a.order_sn', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('a.pay_sn', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('b.nick_name', '%' . trim($keyword) . '%', 'OR');
            $query->whereLike('b.phone', '%' . trim($keyword) . '%');
        }
    }

    /**
     * 获取分页列表
     * @param $status
     * @param $jump_type
     * @param $keyword
     * @param $current_page
     * @param $list_rows
     * @param string $field
     * @return array
     */
    public function getPageData($user_id, $current_page, $list_rows, $field = '*')
    {
        $dataList = $this
            ->UserId($user_id)
            ->field($field)
            ->order('create_time', 'desc')
            // ->fetchSql(true)
            // ->select();
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        // var_dump($dataList);exit;
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }

    /**
     * 添加用户收益记录
     * @param array $earnings
     * $earnings['user_id']  用户id
     * $earnings['type']  收益类型 1返现2佣金3任务4提现
     * $earnings['detail']  说明
     * $earnings['last_price']  金上次额
     * $earnings['price']  金额
     * $earnings['change']  改变情况  add增加  sub减少
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addEarnings($earnings = [])
    {
        $in_earnings = [
            'update_time' => time(),
            'create_time' => time(),
            'create_date' => date("Y-m-d H:i:s"),
            'order_sn' => $earnings['order_sn'],
            'pay_sn' => $earnings['pay_sn'],
            'user_id' => $earnings['user_id'],
            'type' => $earnings['type'],
            'detail' => $earnings['detail'],
            'last_price' => $earnings['last_price'],
            'price' => $earnings['price'],
            'deposit' => $earnings['deposit'],
            'deposit_sn' => $earnings['deposit_sn'],
            'change' => $earnings['change'],
            'check' => $earnings['check'],
            'mold' => $earnings['mold'],
            'wxopen_id' => $earnings['wxopen_id'],
        ];
        $id = $this->insertGetId($in_earnings);
        if (empty($id)) {
            return false;
        }
        if ($earnings['type'] == 4) {
            $up_data = [
                'check' => 2,
                'check_time' => date("Y-m-d H:i:s")
            ];
            $this->where('id', $id)->update($up_data);
            $user_model = new  UserModel();
            $ret = $user_model->payUserDeposit('earnings', $id);
            if ($ret['code'] == 1) {
                return true;
            }
            return false;
//            if (floatval($earnings['deposit']) < 100) {
//                $up_data = [
//                    'check' => 2,
//                    'check_time' => date("Y-m-d H:i:s")
//                ];
//                $this->where('id', $id)->update($up_data);
//                $user_model = new  UserModel();
//                $ret = $user_model->payUserDeposit('earnings', $id);
//                if ($ret['code'] == 1) {
//                    return true;
//                }
//                return false;
//            }
        }
        return true;
    }

    /**
     * 获取冻结部分的收益金额
     * @param string $user_id
     * @return float|int
     */
    public static function getFreeze($user_id = '')
    {
        $map = [
            'change' => 'add',
            'user_id' => $user_id
        ];
        $day_7 = time() - (3600 * 24 * 7);
        $price = self::where($map)->where('create_time', '>', $day_7)->sum('price');
        if (empty($price)) {
            return 0;
        }
        return round($price, 2);
    }

    /**
     * 获取当天提现的金额
     * @param string $user_id
     * @return float|int
     */
    public static function getDayDeposit($user_id = '')
    {
        $map = [
            'user_id' => $user_id,
            'type' => 4
        ];
        $start_time = strtotime(date("Y-m-d"));
        $end_time = strtotime(date("Y-m-d") . " 23:59:59");
        $deposit = self::where($map)->whereBetween('create_time', $start_time . "," . $end_time)->sum('price');
        if (empty($deposit)) {
            return 0;
        }
        return $deposit;
    }

    /**
     * 验证提现审核通过的订单资金到账情况
     * @param int $end_time
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function checkDepositAccount($end_time = 0)
    {
        $map = [
            'type' => 4,
            'check' => 2,
            'status' => 1
        ];
        $list = self::where($map)->field('id,deposit_sn,deposit')->where('create_time', '>', $end_time)->select();
        if (empty($list)) {
            return true;
        }
        $wx_pay3_tool = new WxV3Pay();
        $index = 1;
        foreach ($list as $value) {
            $res = $wx_pay3_tool->queryUserDeposit($value['deposit_sn']);
            if ($res['code'] == 1) {
                $up_data = [
                    'status' => 2
                ];
                self::where('id', $value['id'])->update($up_data);
            }
            if ($index % 10 == 0) {
                sleep(1);
            }
            $index++;
        }
    }
}
